/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("Ok3w_Article",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.MyTable.IServices;
using System.Collections;
using VOL.Core.DBManager;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using VOL.Core.Files;
using VOL.Core.Filters;
using VOL.Core.Utilities;
using VOL.Core.ManageUser;
using VOL.Core.Extensions;
using Org.BouncyCastle.Asn1.Cms;
using sysio = System.IO;
using sysnet = System.Net;
using SkiaSharp;

namespace VOL.MyTable.Controllers
{

    public partial class Ok3w_ArticleController
    {

        private readonly IOk3w_ArticleService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public Ok3w_ArticleController(
            IOk3w_ArticleService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }
        /*  [DisableRequestSizeLimit]
          public override IActionResult Upload(IEnumerable<IFormFile> fileInput)
          {
              return base.Upload(fileInput);
          }*/
        [HttpPost, Route("GetPageData"), AllowAnonymous]
        [ApiActionPermission()]
        public override ActionResult GetPageData([FromBody] PageDataOptions loadData)
        {

            return base.GetPageData(loadData);
        }

        [HttpPost, Route("get_ok3w_for_front"), AllowAnonymous]//传数据给前端 map 
        public dynamic get_ok3w_for_front(Guid qid, string lstype)
        {

            /* Sys_User user = DBServerProvider.DbContext.Set<Sys_User>().Where(x => x.UserName == "admin")
                     .FirstOrDefault();
             string token = JwtHelper.IssueJwt(new UserInfo()
             {
                 User_Id = user.User_Id,
                 UserName = user.UserName,
                 Role_Id = user.Role_Id
             });
             user.Token = token;
             DBServerProvider.DbContext.Update(user);
             DBServerProvider.DbContext.SaveChanges();
            // UserContext.Current.LogOut(user.User_Id);*/

            Hashtable rtn_hst = new Hashtable();

            List<Ok3w_Article> ok3W_Article_list = DBServerProvider.DbContext.Set<Ok3w_Article>().ToList();
            List<Ok3w_Class> Ok3w_Class_list = DBServerProvider.SqlDapper.QueryList<Ok3w_Class>("select * from Ok3w_Class", "").ToList();
            var rnttable = from q in ok3W_Article_list
                           join q2 in Ok3w_Class_list on q.ClassID equals q2.id
                           select new
                           {
                               q2.SortName,
                               q,
                           };
            List<dynamic> online_class_list = DBServerProvider.SqlDapper.QueryList<dynamic>("select distinct a.SortName text from Ok3w_Class a,Ok3w_Article b where b.ClassID=a.id", "").ToList();
            if (lstype == "all")
            {
                rtn_hst.Add("alltable", rnttable);
            }
            else
            {
                rnttable = rnttable.Where(w => w.q.ok3w_article_id == qid).AsQueryable();
                rtn_hst.Add("alltable", rnttable);
            }
            List<dynamic> tree_data = DBServerProvider.SqlDapper.QueryList<dynamic>(" select sortname name,id,parentid parentId,id classid from ok3w_class", "").ToList();


            rtn_hst.Add("online_class_list", online_class_list);
            rtn_hst.Add("tree_data", tree_data);
            return rtn_hst;
        }

        [HttpPost, Route("getFileInfo"), AllowAnonymous]//获取文件信息
        public List<dynamic> GetFileInfo(int id)
        {
            List<dynamic> list = new List<dynamic>();
            try
            {
                string sql = "select owc.SortName,owa.Title,owa.AttachmentURL,owa.Content  from Ok3w_Article owa join Ok3w_Class owc on owa.ClassID =owc.id where owa.id=" + id;
                list = DBServerProvider.SqlDapper.QueryList<dynamic>(sql, null).ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return list;
        }

        [HttpPost, Route("getSampleLevelLink"), AllowAnonymous]//获取同级别的文件链接
        public List<dynamic> GetSampleLevelLink(int id)
        {
            List<dynamic> list = new List<dynamic>();
            try
            {
                string sql = "select owa.id,owa.title from Ok3w_Article owa join Ok3w_Class owc on owa.ClassID=owc.id where owa.id!=" + id + " and classID in (select ClassID from Ok3w_Article owa where id=" + id + ") order by owa.CreateDate asc";
                list = DBServerProvider.SqlDapper.QueryList<dynamic>(sql, null).ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return list;
        }

        [HttpPost, Route("getDocumentRate"), AllowAnonymous]//获取文档占比
        public List<dynamic> GetDocumentRate()
        {
            List<dynamic> classList = new List<dynamic>();
            try
            {
                string classSql = "select id,SortName name,isnull(ParentID,0) parentID,0 'value' from Ok3w_Class order by parentID desc";
                classList = DBServerProvider.SqlDapper.QueryList<dynamic>(classSql, null).ToList();
                string articleSql = "select count(*) num,ClassID from Ok3w_Article owa  group by ClassID";
                List<dynamic> articleList = DBServerProvider.SqlDapper.QueryList<dynamic>(articleSql, null).ToList();
                classList.ForEach(x =>
                {
                    articleList.ForEach(y =>
                    {
                        if (x.id == y.ClassID)
                        {
                            x.value += y.num;
                        }
                    });
                    classList.ForEach(y =>
                    {
                        if (x.parentID == y.id)
                        {
                            y.value += x.value;
                        }
                    });
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return classList;
        }

        [HttpPost, Route("updateDownloadCount"), AllowAnonymous]//更新文档下载次数
        [ApiActionPermission()]
        public WebResponseContent UpdateDownloadCount(int id)
        {
            WebResponseContent webResponse = new WebResponseContent();
            var dapper = DBServerProvider.SqlDapper;
            string updateStatus = "";
            try
            {
                dapper.BeginTrans();
                updateStatus = "update Ok3w_Article set downloadCount=downloadCount+1 where id=@value";
                var data = dapper.ExcuteNonQuery(updateStatus, new { value = id });
                dapper.Commit();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                dapper.Rollback();
            }
            return webResponse.OK();
        }

        [HttpPost, Route("getDownloadCount"), AllowAnonymous]//获取文档下载次数
        public List<dynamic> GetDownloadCount()
        {
            List<dynamic> list = new List<dynamic>();
            try
            {
                string sql = "select top 20 downloadCount,Title from Ok3w_Article owa group by downloadCount,Title order by downloadCount desc";
                list = DBServerProvider.SqlDapper.QueryList<dynamic>(sql, null).ToList();
                list.Reverse();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return list;
        }

        [HttpPost, Route("getUploadRankInfo"), AllowAnonymous]//获取上传排行
        public List<dynamic> GetUploadRankInfo()
        {
            List<dynamic> list = new List<dynamic>();
            try
            {
                string sql = "select top 20 count(*) num,Creator from Ok3w_Article owa group by Creator order by count(*) desc";
                list = DBServerProvider.SqlDapper.QueryList<dynamic>(sql, null).ToList();
                list.Reverse();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return list;
        }

        [HttpPost, Route("create_zip_rfqfiles"), AllowAnonymous]//将下载导航节点及其所有子节点下的文件打包成zip压缩包
        public ActionResult create_zip_rfqfiles(int ClassID)
        {
            string path = "";
            List<int> class_id = new List<int>();
            class_id.Add(ClassID);
            List<string> out_files = new List<string>();
            while (true)
            {
                if (class_id.Count == 0)
                {
                    break;
                }
                List<int> children_class_id = DBServerProvider.SqlDapper.QueryList<int>("select id from Ok3w_Class where ParentID = " + class_id[0], "").ToList();                
                children_class_id.ForEach(id =>
                {
                    class_id.Add(id);
                });
                List<string> files = DBServerProvider.DbContext.Set<Ok3w_Article>().Where(w => w.ClassID == class_id[0]).Select(s => s.AttachmentURL).ToList();
                List<int> files_id = DBServerProvider.DbContext.Set<Ok3w_Article>().Where(w => w.ClassID == class_id[0]).Select(s => s.id).ToList();
                files_id.ForEach(id =>{UpdateDownloadCount(id);});//文档下载次数也需要更新
                class_id.RemoveAt(0);
                for (int i = 0; i < files.Count; i++)
                {
                    if (!string.IsNullOrEmpty(files[i]))
                    {
                        var mmf = files[i].Split(",");
                        if (mmf.Length > 1)//多个附件的情况
                        {
                            for (int ii = 0; ii < mmf.Length; ii++)
                            {
                                out_files.Add(("wwwroot/" + mmf[ii]).MapPath());
                            }
                        }
                        else
                        {
                            out_files.Add(("wwwroot/" + files[i]).MapPath());
                        }
                    }
                }
            }
            path = Commpress.Compress(Commpress.Fetch(out_files));
            return File(sysio.File.ReadAllBytes(path), sysnet.Mime.MediaTypeNames.Application.Octet, "");
        }
    }
}
